<?php
declare (strict_types = 1);

namespace app\command;

use app\tool\Http;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class News extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('news')
            ->setDescription('the news command');
    }

    protected function execute(Input $input, Output $output)
    {
        $res = Http::get('https://ogcmn.one.gov.hk/ogcmn/service/list/catwc/OGCMN*?lang=sc');
        $res = str_replace('NotiList(', '', $res);
        $res = mb_substr($res, 0, -2);
        $res = json_decode($res);
        $res = $res->notifications;
        foreach ($res as $k) {
            $row = \app\model\News::where(['unique' => $k->id])->find();
            if (!$row) {
                $detail = Http::get('https://ogcmn.one.gov.hk/ogcmn/service/noti/detail/'.$k->id);
                $detail = str_replace('NotiDetail(', '', $detail);
                $detail = mb_substr($detail, 0, -2);
                $detail = json_decode($detail);
                $msg_sc = json_decode($detail->msg_sc);
                $msg_tc = json_decode($detail->msg_tc);
                $msg_sc=$msg_sc->body;
                $msg_tc=$msg_tc->body;
                $msg_sc = implode('\\n',array_column($msg_sc,'val'));
                $msg_tc = implode('\\n',array_column($msg_tc,'val'));

                \app\model\News::create([
                    'users_id' => 3,
                    'class_id' => 9,
                    'issuer_id' => 23,
                    'title_t' => $detail->subject_tc,
                    'title_s' => $detail->subject_sc,
                    'content_t' => $msg_tc,
                    'content_s' => $msg_sc,
                    'unique' => $k->id
                ]);
            }
        }
        $output->writeln('success');
    }
}
